package com.apestech.framework.run.callback;

import java.sql.Savepoint;
import java.util.Vector;

import com.apestech.framework.db.SqlSession;
import com.apestech.framework.run.core.DBExec;
import com.apestech.framework.util.DBUtil;

public abstract class SaveTransactionThreadCallBack implements ThreadCallBackHandler {
	
	private String dbName;
	private Vector<Object> param;
	
	public SaveTransactionThreadCallBack(String dbName, Vector<Object> param){
		this.dbName=dbName;
		this.param=param;
	}

	@Override
	public void run() throws Exception {
		Savepoint sp=null;
		DBExec db=null;
		try{
			db=new DBExec(DBUtil.getDataSource(dbName));
			db.setAutoCommit(false);
			sp=run(db.getSession(),this.param);
		} catch(Exception e){
			if(sp!=null){  
                try {  
                    db.rollback(sp);  //回滚到上一个保存点  但是事务还是没有结束   
                } catch (Exception e1) {  
                	throw e1;
                }  
            } else {
            	throw e;
            }  
		} finally {
			try {  
                db.commit();  //使用 "保存点"后依然提交
                db.close(); 
                db=null;
                sp=null;
            } catch (Exception e2) {
            	throw e2;
            }
		}
	}
	
	protected abstract Savepoint run(SqlSession cn, Vector<Object> param) throws Exception;
	
}
